# coding:utf-8
from common.utils import login_for_background_md, login_for_background_zb, regular_many_kind_of_name
from base.base_config import *
from common.check import check_response_status
from data import initialization_data
import json


# 总部登陆
session_zb = login_for_background_zb()
# 门店登陆
session_md = login_for_background_md()


# 商品编号
def many_kinds_of_goodno(goodtype):
    auto_num_url = BASE_URL + '/Goods/GetGoodsNo'
    auto_num_data = {"GoodsType": goodtype}
    auto_num_res = session_md.post(url=auto_num_url, headers=BASE_HEADER, json=auto_num_data)
    check_response_status(auto_num_res)
    goodno = auto_num_res.json()["GoodsNo"]
    return goodno


class InitializationChain(object):
    # 共用角色
    def add_sharing_employee(self):
        """获取收银台视图"""
        getUI_url = BASE_URL_ZB + '/Global/GetSvcEmpXmlUI'
        getUI_res = session_zb.post(url=getUI_url, headers=BASE_HEADER)
        check_response_status(getUI_res)

        xmlmenu = getUI_res.json()["rows"][0]["XmlMemuID"]  # 儿童收银台视图

        '''添加共用角色'''
        add_employee_url = BASE_URL_ZB + '/Organization/AddPublicEmployeeLevel'
        data = {
            "ID": "",
            "LevelName": regular_many_kind_of_name("共用角色", "ZB", "共用角色"),
            "Summary": "",
            "BusinessType": "4",
            "OpRight": "1",
        }
        employee_res = session_zb.post(url=add_employee_url, json=data, headers=BASE_HEADER)
        check_response_status(employee_res)

        employee_id = employee_res.json()['ID']  # 共用角色ID

        '''保存收银台视图到共用角色'''
        save_xml_url = BASE_URL_ZB + '/Global/SaveSvcEmpXmlUI'
        save_xml_data = {
            "EmpViewStr": '[{"XmlMemuID": '+xmlmenu+', "IsActivityUI": True}]',
            "EmpLevelID": employee_id
        }
        save_res = session_zb.post(url=save_xml_url, json=save_xml_data, headers=BASE_HEADER)
        check_response_status(save_res)
        return employee_id

    # 用户管理
    def add_user(self):
        """获取超级管理员ID"""
        get_adminID_url = BASE_URL_ZB + '/Organization/DTOGetEmpList'
        get_adminID_data = {
            "RealName": "",
            "LoginName": "",
            "BusinessID": "",
            "IsEnable": "TRUE",
            "page": "1",
            "rows": "15",
        }
        get_adminID_res = session_zb.post(url=get_adminID_url, headers=BASE_HEADER, json=get_adminID_data)
        check_response_status(get_adminID_res)

        adminID = str()
        for users in get_adminID_res.json()['rows']:
            if users['LoginName'] == 'admin':
                adminID = users['ID']
                break

        '''获取所有门店ID（包括总部）'''
        bussiness_ids_md = DB_ZB.ExecQuery("select ID from Mall_Business where BusinessType=4")
        bussiness_ids_zb = DB_ZB.ExecQuery("select ID from Mall_Business where BusinessType=1")

        employee_id = InitializationChain().add_sharing_employee()  # 共用角色ID

        # 组合参数
        DeparmentID_List = list()
        DeparmentID_List.append(json.dumps({"bid": str(bussiness_ids_zb[0][0]), "roleid": adminID}))
        for md_id in bussiness_ids_md:
            data = {"bid": str(md_id[0]), "roleid": employee_id}
            DeparmentID_List.append(json.dumps(data))  # 字典转字符串,再append到列表
        text = '[' + ','.join(DeparmentID_List) + ']'  # join()：# 将列表中的每个元素连接起来，转化为字符串；并整理格式

        '''总部添加门店角色'''
        edit_users_data = {
            "ID": adminID,
            "LoginName": "admin",
            "Password": "",
            "RealName": "超级管理员",
            "Phone": "",
            "DeparmentID": text,
            "CashAble": "FALSE",
            "DefaultRoleId": "c3b7d344-98e7-474f-a15c-a4c000f9f850",

        }
        edit_employee_url = BASE_URL_ZB + '/Organization/DTOEditEmployee'
        res = session_zb.post(url=edit_employee_url, json=edit_users_data, headers=BASE_HEADER)
        check_response_status(res)

        '''获取总部切换门店所属角色ID'''
        infos = DB_ZB.ExecQuery("select e.ID,m.MallURL from Mall_EmployeeLevel e join Mall_MallInstance m on e.OwnedMall=m.Mall where e.TargetLevel='"+employee_id+"' and e.IsDelete=0")
        role_list = list()
        for info in infos:
            data = {"roleid": str(info[0])}
            if not info[1]:
                data["loginname"] = "cjz"
            else:
                if len(info[1]) < 5:
                    raise ValueError("请检查mallurl格式是否正确：{}".format(info[1][-1]))
                else:
                    if info[1][-1] == '/':
                        data["loginname"] = info[1][-5:-1]  # 取端口号
                    else:
                        data["loginname"] = info[1][-4:]  # 取端口号
            role_list.append(data)

        for role in role_list:
            '''总部切换到门店'''
            switch_to_md_url = BASE_URL_ZB + '/DTOChangeRole'
            switch_data = {
                "LevelID": role["roleid"]
            }
            switch_to_md_res = session_zb.post(url=switch_to_md_url, headers=BASE_HEADER, json=switch_data)
            check_response_status(switch_to_md_res)

            '''总部添加门店用户'''
            add_md_user_url = BASE_URL_ZB + '/Organization/DTOAddBizEmployee'
            add_md_user_data = {
                "ID": "",
                "LoginName": role["loginname"],
                "Password": "1",
                "RealName": "初始化账号",
                "Phone": "",
                "CashAble": "TRUE",
                "DeparmentID": '[{"roleid": '+employee_id+'}]',
                "DefaultRoleId": employee_id,
                "DataSelectGet": "0",
                "DateSelectTotle": "0",
                "Terminal": "",
            }
            add_md_user_res = session_zb.post(url=add_md_user_url, headers=BASE_HEADER, json=add_md_user_data)
            try:
                check_response_status(add_md_user_res)
            except:
                if "用户名已存在" in add_md_user_res.json()["ResponseStatus"]["Message"]:
                    log.info(add_md_user_res.text)
                else:
                    raise Exception(add_md_user_res.text)
            finally:
                # 切换回去总部
                role_zb = str(DB_ZB.ExecQuery("select ID from Mall_EmployeeLevel where IsSys=1")[0][0])
                switch_data["LevelID"] = role_zb
                switch_to_md_res = session_zb.post(url=switch_to_md_url, headers=BASE_HEADER, json=switch_data)
                check_response_status(switch_to_md_res)
                pass

    # 商品分类
    def add_good_class(self):
        """获取商品分类编号"""
        good_class_code_url = BASE_URL_ZB + '/Goods/DTONewGoodClassCode'
        good_class_code_res = session_zb.post(url=good_class_code_url, headers=BASE_HEADER)
        check_response_status(good_class_code_res)

        code = good_class_code_res.json()["NewClassCode"]

        '''新增商品分类'''
        add_good_class_url = BASE_URL_ZB + '/Goods/DTOAddGoodsClass'
        add_good_class_data = {
            "id": "",
            "ClassName": regular_many_kind_of_name("一级商品分类", "ZB", "商品分类"),
            "SuperiorId": "",
            "Code": code
        }
        add_good_class_res = session_zb.post(url=add_good_class_url, json=add_good_class_data, headers=BASE_HEADER)
        check_response_status(add_good_class_res)

    # 会员级别
    def add_leaguerr_level(self):
        leaguer_level_url = BASE_URL_ZB + '/Leaguer/DTOAddLeaguerLevel'

        datalist = initialization_data.leaguerlevel_data_manage()  # 会员级别数据

        for data in datalist:
            leaguer_level_res = session_zb.post(url=leaguer_level_url, json=data, headers=BASE_HEADER)
            check_response_status(leaguer_level_res)

    # 仓库
    def add_warehouse(self):
        """获取仓库编号"""
        getnum_url = BASE_URL + '/Global/DTOGetAutoNum'
        data = {
            "Length": 4,
            "NumType": 23
        }
        getnum_res = session_md.post(url=getnum_url, json=data)
        check_response_status(getnum_res)

        num = getnum_res.json()["Number"]

        '''添加仓库'''
        addstock_url = BASE_URL + '/Inventory/DTOAddStock'
        stock_data = {
            "IsAllowEditSecSupplementPrice": "TRUE",
            "ID": "",
            "Num": num,
            "Name": regular_many_kind_of_name("零食仓库", "MD", "仓库"),
            "Address": "",
            "IsCanNeg": "FALSE",
            "IsMaster": "FALSE",
            "IsBottomLineNotice": "FALSE",
            "BottomLineNum": "",
            "UpperLimitNum": ""
        }
        addstock_res = session_md.post(url=addstock_url, json=stock_data, headers=BASE_HEADER)
        check_response_status(addstock_res)

    # 收银终端
    def add_cash_terminal(self):
        """获取收银终端编号"""
        getnum_url = BASE_URL + '/Global/DTOGetAutoNum'
        data = {
            "Length": 4,
            "NumType": 19
        }
        getnum_res = session_md.post(url=getnum_url, json=data)
        check_response_status(getnum_res)

        num = getnum_res.json()["Number"]

        '''添加收银终端'''
        terminal_url = BASE_URL + '/Terminal/AddBusinessTerminal'
        terminal_data = {
            "TerNum": num,
            "TerminalName": regular_many_kind_of_name("收银终端", "MD", "收银终端"),
            "CashAble": "TRUE",  # 是否收银
            "IsPrint": "TRUE",  # 是否打印
            "Address": "",
            "Mac": "",
            "IsEnable": "TRUE",  # 是否启用
            "Summary": "",
            "CashType": "1",
            "TypeName": "1",
            "StockHouse": None,  # 售卖仓库
            "LeaseStockHouse": None,  # 租赁仓库
            "ID": "",
        }
        termial_res = session_md.post(url=terminal_url, json=terminal_data, headers=BASE_HEADER)
        check_response_status(termial_res)

    # 支付方式
    def add_pay_method(self):
        """获取支付类型"""
        get_paytype_url = BASE_URL + '/Global/DTOGetBusinessKind'
        data = {}
        get_paytype_res = session_md.post(url=get_paytype_url, headers=BASE_HEADER, json=data)
        check_response_status(get_paytype_res)

        for btype in get_paytype_res.json()["BusinessType"]:
            add_paypay_url = BASE_URL + '/Global/DTOAddPayType'
            data = {
                "IsEnable": "true",
                "IsCashPayType": "false",
                "PayKind": btype["Value"],
                "IsAllTerminal": "true",
                "IsCountMoney": "false",
                "ID": "",
                "PayName": btype["Text"],
                "Terlist": "",
                "PaySetting": "0",
                "Num": "",
                "CashSort": "99"
            }
            add_paypay_res = session_md.post(url=add_paypay_url, headers=BASE_HEADER, json=data)
            try:
                check_response_status(add_paypay_url)
            except Exception as msg:
                if add_paypay_res.json()["ResponseStatus"]["ErrorCode"] == "6004":
                    log.info(add_paypay_res.text)
                else:
                    raise Exception(add_paypay_res.text)

    # 开启代币/金币有效期
    def open_coin_period(self):
        coin_perid_switch_url = BASE_URL_ZB + '/Global/DTOPostMallConfigTokenPeriodSet'
        data = {
            "ID": 62,
            "ConfigValue": True,
            "GoldID": 95,
            "GoldConfigValue": True
        }
        response = session_zb.post(url=coin_perid_switch_url, headers=BASE_HEADER, json=data)
        check_response_status(response)

    # 游戏币
    def game_coin_meal(self):
        """新增游戏币套餐"""
        good_class = str(DB_MD.ExecQuery("select TOP 1 ID from mall_goodclass where IsDelete=0 and IsEnable=1 order by CreateTime desc")[0][0])
        add_coin_url = BASE_URL + '/Coin/DTOPostCoinMeal?Group=&GoodCls='+good_class+'&GroupName=游戏币'
        game_coin_data = initialization_data.gamecoin_data_manage()  # 游戏币用例

        for data in game_coin_data:
            res = session_md.post(url=add_coin_url, headers=BASE_HEADER, json=data)
            check_response_status(res)

    # 入会套餐
    def leaguer_join_meal(self):
        """新增入会套餐"""
        leaguer_join_url = BASE_URL + '/Leaguer/DTOAddChargeJoinNew'
        leaguer_join_data = initialization_data.leaugerjoin_data_manage()  # 入会套餐用例

        for data in leaguer_join_data:
            res = session_md.post(url=leaguer_join_url, headers=BASE_HEADER, json=data)
            check_response_status(res)

    # 预存款
    def charge_meal(self):
        """新增预存款套餐"""
        charge_meal_url = BASE_URL + '/Leaguer/DTOAddCharge'
        charge_meal_data = initialization_data.charge_data_manage()  # 预存款用例

        for data in charge_meal_data:
            res = session_md.post(url=charge_meal_url, headers=BASE_HEADER, json=data)
            check_response_status(res)

    # 零售商品
    def retailgoods_meal(self):
        """新增零售套餐"""
        retailgoods_url = BASE_URL + '/GoodsBase/DTOAddNormalGoodsSet'
        retailgoods_data = initialization_data.retailgoods_data_manage()  # 零售商品用例

        for data in retailgoods_data:
            res = session_md.post(url=retailgoods_url, headers=BASE_HEADER, json=data)
            check_response_status(res)


# 基础数据接口套件
def basic_setting_suit():
    initializationChain.add_user()  # 添加用户&角色
    initializationChain.add_good_class()  # 添加商品分类
    initializationChain.add_leaguerr_level()  # 添加会员级别
    initializationChain.add_warehouse()  # 添加仓库
    initializationChain.add_cash_terminal()  # 添加收银终端
    initializationChain.add_pay_method()  # 添加支付方式
    initializationChain.open_coin_period()  # 开启代币/金币有效期
    pass


# 商品接口套件
def goods_suit():
    initializationChain.game_coin_meal()  # 游戏币套餐
    # initializationChain.charge_meal()  # 预存款套餐
    # initializationChain.retailgoods_meal()  # 零售商品套餐
    initializationChain.leaguer_join_meal()  # 会员入会套餐
    pass


if __name__ == '__main__':
    initializationChain = InitializationChain()
    # basic_setting_suit()
    goods_suit()
